package com.example.za.account.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.example.za.account.R;
import com.example.za.account.activity.RecordActivity;
import com.example.za.account.adapter.ExpenseSwipeAdapter;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.dao.ExpenseDao;
import com.example.za.account.model.Expense;
import com.example.za.account.utils.Constant;
import com.example.za.account.utils.DateUtils;
import com.example.za.account.utils.ScreenUtils;
import com.example.za.account.utils.T;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class ShowExpenseFragment extends ListFragment {

    @BindView(android.R.id.list)
    SwipeMenuListView mListFinance;
    private ExpenseDao mExpenseDao;
    private ExpenseSwipeAdapter mExpenseSwipeAdapter;
    private onExpenseChangeListener mOnExpenseChangeListener;
    private List<Expense> mExpenses;
    private int mType;

    Unbinder unbinder;
    private View rootView;

    public static ShowExpenseFragment getInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.TYPE_DATE, type);
        ShowExpenseFragment showExpenseFragment = new ShowExpenseFragment();
        showExpenseFragment.setArguments(bundle);
        return showExpenseFragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof onExpenseChangeListener) {
            mOnExpenseChangeListener = (onExpenseChangeListener) activity;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mType = getArguments().getInt(Constant.TYPE_DATE);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_finance, container, false);
            unbinder = ButterKnife.bind(this, rootView);
            mExpenseDao = new ExpenseDao(getActivity());
            switch (mType) {
                case Constant.TYPE_TODAY:
                    mExpenses = mExpenseDao.getPeriodExpense(DateUtils.getTodayStart(), DateUtils.getTodayEnd(),
                            AccountApplication.sUser.getmId());
                    mExpenseSwipeAdapter = new ExpenseSwipeAdapter(getActivity(), mExpenses, true);
                    break;
                case Constant.TYPE_WEEK:
                    mExpenses = mExpenseDao.getPeriodExpense(DateUtils.getWeekStart(),
                            DateUtils.getWeekEnd(), AccountApplication.sUser.getmId());
                    mExpenseSwipeAdapter = new ExpenseSwipeAdapter(getActivity(), mExpenses, false);
                    break;
                case Constant.TYPE_MONTH:
                    mExpenses = mExpenseDao.getPeriodExpense(DateUtils.getMonthStart(),
                            DateUtils.getMonthEnd(), AccountApplication.sUser.getmId());
                    mExpenseSwipeAdapter = new ExpenseSwipeAdapter(getActivity(), mExpenses, false);
                    break;
                default:
                    break;
            }
            setListAdapter(mExpenseSwipeAdapter);
            SwipeMenuCreator creator = new SwipeMenuCreator() {
                @Override
                public void create(SwipeMenu menu) {
                    SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                    deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                    deleteItem.setWidth(ScreenUtils.dp2px(getActivity(), 80));
                    deleteItem.setIcon(R.drawable.btn_delete);
                    menu.addMenuItem(deleteItem);
                }
            };
            mListFinance.setMenuCreator(creator);
            mListFinance.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                    if (mExpenseDao.deleteExpense((Expense) mExpenseSwipeAdapter.getItem(mExpenses.size() - 1 - position))) {
                        T.showShort(getActivity(), getString(R.string.delete_succeed));
                        mExpenses.remove(mExpenses.size() - 1 - position);
                        mExpenseSwipeAdapter.setDate(mExpenses);
                        EventBus.getDefault().post("expense_deleted");
                        invalidateUI();
                    } else {
                        T.showShort(getActivity(), getString(R.string.delete_fail));
                    }
                    return false;
                }
            });
        }


        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    private void invalidateUI() {
        if (mOnExpenseChangeListener != null) {
            float expense = 0;
            switch (mType) {
                case Constant.TYPE_TODAY:
                    expense = mExpenseDao.getPeriodSumExpense(DateUtils.getTodayStart(),
                            DateUtils.getTodayEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_WEEK:
                    expense = mExpenseDao.getPeriodSumExpense(DateUtils.getWeekStart(),
                            DateUtils.getWeekEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_MONTH:
                    expense = mExpenseDao.getPeriodSumExpense(DateUtils.getMonthStart(),
                            DateUtils.getMonthEnd(), AccountApplication.sUser.getmId());
                    break;
                default:
                    break;
            }
            mOnExpenseChangeListener.updateExpense(expense);
        }
    }

    public interface onExpenseChangeListener {
        void updateExpense(float expense);
    }

    @Subscribe
    public void refreshUI(String message) {
        if (TextUtils.equals(message, "expense_updated") && mExpenseSwipeAdapter != null) {
            switch (mType) {
                case Constant.TYPE_TODAY:
                    mExpenses = mExpenseDao.getPeriodExpense(DateUtils.getTodayStart(),
                            DateUtils.getTodayEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_WEEK:
                    mExpenses = mExpenseDao.getPeriodExpense(DateUtils.getTodayStart(),
                            DateUtils.getWeekEnd(), AccountApplication.sUser.getmId());
                    break;
                case Constant.TYPE_MONTH:
                    mExpenses = mExpenseDao.getPeriodExpense(DateUtils.getMonthStart(),
                            DateUtils.getMonthEnd(), AccountApplication.sUser.getmId());
                    break;
                default:
                    break;
            }
            mExpenseSwipeAdapter.setDate(mExpenses);
            invalidateUI();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mOnExpenseChangeListener = null;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Expense expense = (Expense) l.getItemAtPosition(mExpenses.size() - 1 - position);
        Intent intent = new Intent(getActivity(), RecordActivity.class);
        intent.putExtra(Constant.RECORD, expense);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

}
